<?php


namespace app\modules\admin\controllers;


use app\common\services\StaticServices;
use app\models\Project;
use yii\base\Exception;
use yii\web\Controller;
use Yii;
use yii\web\Response;

class ProjectController extends Controller {
  public function actionIndex()
  {
    $p = intval(Yii::$app->request->get("p", 1));
    $pro_info = Project::find();

    $page_size = StaticServices::$page;
    $total_count = $pro_info->count();
    $total_page = ceil($total_count / $page_size);

    $list = $pro_info->offset(($p - 1) * $page_size)->orderBy(['create_time' => SORT_DESC])->limit($page_size)->all();
    return $this->render('index', ['list' => $list, 'p' => $p, 'total_page' => $total_page]);
  }


  public function actionSet()
  {
    $pro_id = intval(Yii::$app->request->get("id", 0));
    $pro_info = [];
    if ($pro_id) {
      $pro_info = Project::find()->where(['id' => $pro_id])->one();
    }

    if (Yii::$app->request->isPost) {
      Yii::$app->response->format = Response::FORMAT_JSON;
      try {
        $pro_title = trim(Yii::$app->request->post('pro_title', ''));
        $cover_img = trim(Yii::$app->request->post('cover_img', ''));
        $pro_content = Yii::$app->request->post("pro_content", '');
        $pro_id = intval(Yii::$app->request->post("pro_id", 0));

        if (mb_strlen($pro_title, 'utf-8') < 1) {
          throw new Exception("请填写动态标题");
        }
        if (mb_strlen($cover_img, 'utf-8') < 1) {
          throw new Exception("请上传动态封面图");
        }
        if (mb_strlen($pro_content, 'utf-8') < 1) {
          throw new Exception("请填写动态具体内容");
        }
        $pro_arr = Project::find()->where(["id" => $pro_id])->one();
        if ($pro_arr) {
          $pro_info = $pro_arr;
        } else {
          $pro_info = new Project();
          $pro_info->create_time = time();
        }
        $pro_info->pro_title = $pro_title;
        $pro_info->cover_img = $cover_img;
        $pro_info->pro_content = $pro_content;
        $pro_info->update_time = time();
        $pro_info->save(0);
        return ['code' => 200, 'msg' => "操作成功"];
      } catch (Exception $e) {
        return ['code' => -200, 'msg' => $e->getMessage()];
      }
    }
    return $this->render('set', ['info' => $pro_info]);
  }

  public function actionOps()
  {
    if (Yii::$app->request->isPost) {
      Yii::$app->response->format = Response::FORMAT_JSON;
      try {
        $pro_id = intval(Yii::$app->request->post('pro_id', 0));
        if ($pro_id) {
          Project::deleteAll(['id' => $pro_id]);
          return ['code' => -200, 'msg' => "操作成功"];
        }
      } catch (Exception $e) {
        return ['code' => -200, 'msg' => $e->getMessage()];
      }
    }
  }
}